package com.grouplay.controller;

import com.grouplay.entity.*;
import com.grouplay.service.IGroupService;
import com.grouplay.service.IInformationService;
import com.grouplay.service.IInvitationService;
import com.grouplay.service.IUserService;
import com.grouplay.utils.CreateMimeMessageUtil;
import com.grouplay.utils.StringValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGroupService groupService;
    @Autowired
    private IInformationService informationService;
    @Autowired
    private IInvitationService invitationService;

    @RequestMapping("/register")
    public @ResponseBody
    Boolean register(User user, HttpSession session, String verificationCode){
        if (user.getEmail() == null
                || !user.getEmail().equals(session.getAttribute("email"))
                || verificationCode == null
                || !verificationCode.equals(session.getAttribute("verificationCode"))
                || user.getName() == null
                || user.getName().length() > 20
                || !StringValidateUtil.isLetterDigitOrChinese(user.getName())
                || user.getPassword() == null
                || user.getPassword().length() < 6
                || user.getPassword().length() > 16
                || !StringValidateUtil.isLetterDigit(user.getPassword())) {
            return false;
        }
        return userService.insert(user);
//            try {
//                userService.insert(user);
//                return true;
//            } catch (Exception e){
//                return false;
//            }
    }

    @RequestMapping("/getVerificationCode")
    public @ResponseBody
    Boolean getVerificationCode(String email, HttpSession session) {
        String verificationCode = "";
        for (int i = 0; i < 6; i ++) {
            verificationCode += (int) (Math.random() * 10);
        }
        try{
            System.out.println(email+" " + verificationCode);
            // 发送验证码
            sendVerificationCode(email, verificationCode,"仅用于注册或修改密码，10分钟内有效");
            session.setAttribute("email", email);
            session.setAttribute("verificationCode", verificationCode);
            session.setMaxInactiveInterval(10*60);
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }
    @RequestMapping("/")
    public String getVerificationCode() {
       return "index";
    }
    @RequestMapping("/login")
    public @ResponseBody
    Boolean login(User user, String remember, HttpSession session, HttpServletRequest request, HttpServletResponse response){
        User u = null;
        if (user != null && user.getEmail() != null && user.getPassword() != null){
            u = userService.login(user.getEmail(), user.getPassword());
        } else {
            String email = null, password = null;
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies){
                if ("email".equals(cookie.getName())){
                    email = cookie.getValue();
                }
                if ("password".equals(cookie.getName())){
                    password = cookie.getValue();
                }
            }
            if (email != null && password != null) {
                u = userService.login(email, password);
            }
        }
        if (u != null){
            session.setAttribute("user", u);
            if ("1".equals(remember)){
                Cookie cookieEmail = new Cookie("email", user.getEmail());
                cookieEmail.setMaxAge(10 * 24 * 60 * 60);
                Cookie cookiePassword = new Cookie("password", user.getPassword());
                cookiePassword.setMaxAge(10 * 24 * 60 * 60);
                response.addCookie(cookieEmail);
                response.addCookie(cookiePassword);
            }
            return true;
        }
        return false;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("email".equals(cookie.getName())){
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
            if ("password".equals(cookie.getName())){
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        session.removeAttribute("user");
        return "redirect:/index.jsp";
    }

    @RequestMapping("/setNewPassword")
    public @ResponseBody
    Boolean setNewPassword(String email, String password, String verificationCode, HttpSession session){
        if (email == null
                || !email.equals(session.getAttribute("email"))
                || verificationCode == null
                || !verificationCode.equals(session.getAttribute("verificationCode"))
                || password == null
                || password.length() < 6
                || password.length() > 16
                || !StringValidateUtil.isLetterDigit(password)){
            return false;
        }
        return userService.setNewPassword(email, password);
    }

    @RequestMapping("/setNewName")
    public @ResponseBody
    Boolean setNewName(HttpSession session, String name){
        if (name == null || name.length() > 20 || name.length() <= 0 || !StringValidateUtil.isLetterDigitOrChinese(name)){
            return false;
        }
        if (session.getAttribute("user") != null){
            User user = (User) session.getAttribute("user");
            user.setName(name);
            if (userService.serNewName(user)) {
                session.setAttribute("user", user);
                return true;
            }
        }
        return false;
    }

    @RequestMapping("/getMyGroups")
    public @ResponseBody
    List<Group> getMyGroups(HttpSession session) {
        System.out.println((User) session.getAttribute("user"));
        if (session.getAttribute("user") != null) {
            return groupService.findAllGroupsByLeaderId(((User) session.getAttribute("user")).getId());
        }
        return new ArrayList<Group>();
    }

    @RequestMapping("/createGroup")
    public @ResponseBody
    Boolean createGroup(Group group, HttpSession session){
        if (session.getAttribute("user") == null) {
            return false;
        }
        return groupService.createGroup((User) session.getAttribute("user"), group);
    }


    @RequestMapping("/sendMessage")
    public @ResponseBody
    Boolean sendMessage(String targetName, String message, HttpSession session){
        if (session.getAttribute("user") == null) {
            return false;
        }
        User user = (User) session.getAttribute("user");
        return informationService.sendInformation(user, targetName, message);
    }

    @RequestMapping("/getTenMessages")
    public @ResponseBody
    List<Information> getTenMessage(HttpSession session){
        if (session.getAttribute("user") == null) {
            return new ArrayList<Information>();
        }
        return informationService.findTenInformationByUser((User) session.getAttribute("user"));
    }


    @RequestMapping("/markRead")
    public @ResponseBody
    Boolean markRead(HttpSession session, Integer id){
        if (session.getAttribute("user") == null) {
            return false;
        }
        return informationService.setHasBeenLookedByIdAndTargetId(id, ((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/getOtherUser")
    public @ResponseBody
    List<User> getOtherUser(HttpSession session, Integer groupId){
        if (session.getAttribute("user") == null && groupId == null) {
            return new ArrayList<User>();
        }
        return groupService.findAllUserNameOfTheGroupByGroupWhileIsNotEnd(groupId, ((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/inviteUserToMyGroup")
    public @ResponseBody
    Boolean inviteUserToMyGroup(HttpSession session, Integer inviteGroupId, String beInvitedUserName){
        if (session.getAttribute("user") == null && inviteGroupId == null && beInvitedUserName == null) {
            return false;
        }
        Integer leaderId =  ((User) session.getAttribute("user")).getId();
        return groupService.sendOneInvitation(inviteGroupId, beInvitedUserName, leaderId);
    }

    @RequestMapping("/inviteMe")
    public @ResponseBody
    List<Invitation> inviteMe(HttpSession session){
        if (session.getAttribute("user") == null) {
            return new ArrayList<Invitation>();
        }
        return invitationService.inviteMe(((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/lookGroupDetails")
    public @ResponseBody
    Group lookGroupDetails(HttpSession session, Integer groupId){
        if (session.getAttribute("user") == null) {
            return null;
        }
        return groupService.findGroupByGroupIdAndUid(groupId, ((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/join")
    public @ResponseBody
    Boolean join(HttpSession session, Integer groupId){
        if (session.getAttribute("user") == null) {
            return false;
        }
        return groupService.joinInGroupByGroupIdAndUid(groupId, ((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/updateMyGroupBudget")
    public @ResponseBody
    Boolean updateMyGroup(Group group, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return false;
        }
        group.setLeaderId(((User) session.getAttribute("user")).getId());
        return groupService.updateGroupBudget(group);
    }

    @RequestMapping("/loadMyJoinGroups")
    public @ResponseBody
    List<Group> loadMyJoinGroups(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return new ArrayList<Group>();
        }
        return groupService.findMyJoinGroupsByUid(((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/loadMyNotPay")
    public @ResponseBody
    List<Group> loadMyNotPay(HttpSession session){
        if (session.getAttribute("user") == null) {
            return new ArrayList<Group>();
        }
        return groupService.findMyJoinGroupsIsEndAndIsNotPay(((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/myBalance")
    public @ResponseBody
    Double myBalance(HttpSession session){
        if (session.getAttribute("user") == null) {
            return null;
        }
        return userService.findBalanceById(((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/transferMoney")
    public @ResponseBody
    Boolean transferMoney(HttpSession session, String transferTargetName, Double transferMoney){
        if (session.getAttribute("user") == null
                || transferTargetName == null
                || "".equals(transferTargetName)
                || transferMoney == null
                || transferMoney <= 0
        ) {
            return false;
        }
        return userService.transferMoney(transferTargetName, ((User) session.getAttribute("user")).getId(), transferMoney);
    }

    @RequestMapping("/pay")
    public @ResponseBody
    Boolean pay(HttpSession session, Integer groupId){
        if (session.getAttribute("user") == null) {
            return null;
        }
        return userService.pay(groupId, ((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/myTransferRecord")
    public @ResponseBody
    List<TransferRecord> myTransferRecord(HttpSession session) {
        if (session.getAttribute("user") == null) {
            return new ArrayList<>();
        }
        return userService.findMyTransferRecordsByUid(((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/endGroup")
    public @ResponseBody
    Boolean endGroup(HttpSession session, Integer groupId) {
        if (session.getAttribute("user") == null || groupId == null) {
            return false;
        }
        return groupService.endGroup(groupId, ((User) session.getAttribute("user")).getId());
    }

    @RequestMapping("/downloadBudgetByGroupId")
    public @ResponseBody
    List<GroupBudget> downloadBudgetByGroupId(HttpSession session, Integer groupId){
        if (session.getAttribute("user") == null || groupId == null) {
            return new ArrayList<>();
        }
        return groupService.findGroupBudgetByGroupId(groupId, ((User) session.getAttribute("user")).getId());
    }

    public void sendVerificationCode(String email, String verificationCode, String subject) throws Exception {
        MimeMessage mimeMessage =CreateMimeMessageUtil.CreateMimeMessage("1196088990@qq.com","dgstxranoqyshhdj");

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);

        mimeMessageHelper.setFrom("1196088990@qq.com");

        mimeMessageHelper.setTo(email);

        mimeMessageHelper.setSubject(subject);
        // 设置消息体
        mimeMessageHelper.setText(verificationCode);
        Transport.send(mimeMessage);
    }
}
